<template>
  <div class="student-supervisor-assignment">
    <div class="page-header">
      <h2>Student-Supervisor Assignment</h2>
    </div>

    <!-- Filter Bar -->
    <el-card class="filter-card">
      <el-form :inline="true" :model="searchForm" class="filter-form">
        <el-form-item label="Student">
          <el-input
            v-model="searchForm.studentName"
            placeholder="Search by student name"
            clearable
            @keyup.enter="loadStudents"
            style="width: 220px;"
          />
        </el-form-item>
        <el-form-item label="Supervisor">
          <el-select
            v-model="searchForm.supervisorId"
            placeholder="Filter by supervisor"
            clearable
            style="width: 220px;"
            @change="loadStudents"
          >
            <el-option label="Unassigned Students" :value="-1" />
            <el-option
              v-for="supervisor in supervisors"
              :key="supervisor.id"
              :label="supervisor.username"
              :value="supervisor.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="loadStudents">
            <el-icon><Search /></el-icon>Search
          </el-button>
          <el-button @click="resetFilter">
            <el-icon><Refresh /></el-icon>Reset
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- Student List -->
    <el-card class="list-card">
      <el-table
        v-loading="loading"
        :data="students"
        border
        stripe
        style="width: 100%"
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="name" label="Name" width="120" />
        <el-table-column prop="username" label="Username" width="120" />
        <el-table-column prop="email" label="Email" width="180" />
        <el-table-column prop="phone" label="Phone" width="120" />
        <el-table-column prop="status" label="Status" width="100">
          <template #default="{ row }">
            <el-tag :type="row.status === 'active' ? 'success' : 'danger'">
              {{ row.status === 'active' ? 'Active' : 'Inactive' }}
            </el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Current Supervisor" width="180">
          <template #default="{ row }">
            <span v-if="findSupervisorName(row.supervisorId)">
              {{ findSupervisorName(row.supervisorId) }}
            </span>
            <el-tag v-else type="info">Unassigned</el-tag>
          </template>
        </el-table-column>
        <el-table-column label="Actions" fixed="right" width="200">
          <template #default="{ row }">
            <el-button
              type="primary"
              link
              @click="handleAssignSupervisor(row)"
            >
              Assign Supervisor
            </el-button>
            <el-button
              v-if="row.supervisorId"
              type="danger"
              link
              @click="handleRemoveSupervisor(row)"
            >
              Remove Supervisor
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- Pagination -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :total="total"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- Assign Supervisor Dialog -->
    <el-dialog
      title="Assign Supervisor"
      v-model="assignDialogVisible"
      width="400px"
    >
      <div v-if="selectedStudent" class="student-info">
        <p><strong>Student:</strong> {{ selectedStudent.name }}</p>
        <p><strong>Username:</strong> {{ selectedStudent.username }}</p>
      </div>
      <el-form
        ref="assignFormRef"
        :model="assignForm"
        :rules="assignRules"
        label-width="100px"
      >
        <el-form-item label="Supervisor" prop="supervisorId">
          <el-select
            v-model="assignForm.supervisorId"
            placeholder="Select Supervisor"
            style="width: 100%"
          >
            <el-option
              v-for="supervisor in supervisors"
              :key="supervisor.id"
              :label="supervisor.username"
              :value="supervisor.id"
            />
          </el-select>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="assignDialogVisible = false">Cancel</el-button>
          <el-button
            type="primary"
            @click="submitAssignment"
            :loading="submitLoading"
          >
            Assign
          </el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, reactive, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Search, Plus, Refresh } from '@element-plus/icons-vue'
import { getAdminStudents } from '../../api/user'
import { assignStudentToSupervisor } from '../../api/student'
import axios from '../../utils/axios'

// Data
const loading = ref(false)
const submitLoading = ref(false)
const students = ref<any[]>([])
const supervisors = ref<any[]>([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const assignDialogVisible = ref(false)
const selectedStudent = ref<any>(null)

// Forms
const searchForm = reactive({
  studentName: '',
  supervisorId: undefined as number | undefined
})

const assignForm = reactive({
  supervisorId: undefined as number | undefined
})

const assignRules = {
  supervisorId: [
    { required: true, message: 'Please select a supervisor', trigger: 'change' }
  ]
}

// Methods
const resetFilter = () => {
  searchForm.studentName = ''
  searchForm.supervisorId = undefined
  loadStudents()
}

const loadStudents = async () => {
  loading.value = true
  try {
    // This is a simplified version - in a real app, you'd use pagination and filters
    const response = await getAdminStudents()
    let filteredStudents = [...response]
    
    // Apply student name filter
    if (searchForm.studentName) {
      filteredStudents = filteredStudents.filter(student => 
        student.name.toLowerCase().includes(searchForm.studentName.toLowerCase())
      )
    }
    
    // Apply supervisor filter
    if (searchForm.supervisorId !== undefined) {
      if (searchForm.supervisorId === -1) {
        // Show only unassigned students
        filteredStudents = filteredStudents.filter(student => !student.supervisorId)
      } else {
        // Show students assigned to specific supervisor
        filteredStudents = filteredStudents.filter(student => 
          student.supervisorId === searchForm.supervisorId
        )
      }
    }
    
    students.value = filteredStudents
    total.value = filteredStudents.length
  } catch (error) {
    console.error('Failed to load students:', error)
    ElMessage.error('Failed to load students')
  } finally {
    loading.value = false
  }
}

const loadSupervisors = async () => {
  try {
    const response = await axios.get('/api/admin/supervisors')
    supervisors.value = response.data
  } catch (error) {
    console.error('Failed to load supervisors:', error)
    ElMessage.error('Failed to load supervisors')
  }
}

const handleSizeChange = (size: number) => {
  pageSize.value = size
  loadStudents()
}

const handleCurrentChange = (page: number) => {
  currentPage.value = page
  loadStudents()
}

const handleAssignSupervisor = (row: any) => {
  selectedStudent.value = row
  assignForm.supervisorId = row.supervisorId
  assignDialogVisible.value = true
}

const handleRemoveSupervisor = (row: any) => {
  ElMessageBox.confirm(
    'Are you sure you want to remove the supervisor assignment?',
    'Warning',
    {
      confirmButtonText: 'Confirm',
      cancelButtonText: 'Cancel',
      type: 'warning'
    }
  )
    .then(() => {
      assignStudentToSupervisor(row.id, null)
        .then(() => {
          ElMessage.success('Supervisor assignment removed successfully')
          loadStudents()
        })
        .catch(error => {
          console.error('Failed to remove supervisor:', error)
          ElMessage.error('Failed to remove supervisor assignment')
        })
    })
    .catch(() => {
      // User canceled
    })
}

const submitAssignment = async () => {
  if (!selectedStudent.value) return
  
  submitLoading.value = true
  try {
    await assignStudentToSupervisor(selectedStudent.value.id, assignForm.supervisorId!)
    ElMessage.success('Supervisor assigned successfully')
    assignDialogVisible.value = false
    loadStudents()
  } catch (error) {
    console.error('Failed to assign supervisor:', error)
    ElMessage.error('Failed to assign supervisor')
  } finally {
    submitLoading.value = false
  }
}

const findSupervisorName = (supervisorId: number | null) => {
  if (!supervisorId) return null
  const supervisor = supervisors.value.find(s => s.id === supervisorId)
  return supervisor ? supervisor.username : null
}

// Lifecycle
onMounted(() => {
  loadStudents()
  loadSupervisors()
})
</script>

<style scoped>
.student-supervisor-assignment {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.filter-card {
  margin-bottom: 20px;
}

.filter-form {
  display: flex;
  align-items: center;
  flex-wrap: wrap;
}

.list-card {
  margin-bottom: 20px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.student-info {
  margin-bottom: 20px;
  padding: 10px;
  background-color: #f8f9fa;
  border-radius: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}
</style> 